package com.dyna.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dyna.core.utils.CollUtil;
import com.dyna.core.utils.SecurityUtil;
import com.dyna.domain.entity.Items;
import com.dyna.domain.entity.VirtualLocker;
import com.dyna.domain.resp.virtual.SelfVirtualLockerResp;
import com.dyna.enums.DeleteValueEnum;
import com.dyna.mapper.ItemsMapper;
import com.dyna.mapper.VirtualLockerMapper;
import com.dyna.service.VirtualLockerService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description items
 * @author zcw
 * @date 2025-02-27
 */
@Slf4j
@AllArgsConstructor
@Service
public class VirtualLockerServiceImpl extends ServiceImpl<VirtualLockerMapper, VirtualLocker> implements VirtualLockerService {

    private final VirtualLockerMapper virtualLockerMapper;
    private final ItemsMapper itemsMapper;

    @Override
    public List<SelfVirtualLockerResp> getList() {
        Long userId = SecurityUtil.getUserId();
        // 1.查询寄存柜中自己的商品
        List<VirtualLocker> virtualLockerList = virtualLockerMapper.querySelfVirtualLocker(userId);
        if (CollUtil.isEmpty(virtualLockerList)) {
            return null;
        }
        Map<Long, List<VirtualLocker>> map = virtualLockerList.stream().filter(f -> f.getCount().intValue() != 0).collect(Collectors.groupingBy(VirtualLocker::getSkuId));
        List<Long> itemIds = virtualLockerList.stream().map(VirtualLocker::getSkuId).distinct().collect(Collectors.toList());
        // 2.查询商品名称
        LambdaQueryWrapper<Items> itemQueryWrapper = new LambdaQueryWrapper<>();
        itemQueryWrapper.in(Items::getItemId, itemIds);
        itemQueryWrapper.eq(Items::getDelFlag, DeleteValueEnum.DELETE.getValue());
        List<Items> itemsList = itemsMapper.selectList(itemQueryWrapper);
        Map<Long, String> itemMap = itemsList.stream().collect(Collectors.toMap(Items::getItemId, Items::getItemName));
        // 3.分组统计商品数量
        List<SelfVirtualLockerResp> result = new ArrayList<>();
        map.forEach((k,v)-> {
            String itemName = itemMap.get(k);
            if (StrUtil.isNotBlank(itemName)) {
                SelfVirtualLockerResp data = new SelfVirtualLockerResp();
                data.setItemId(k);
                data.setItemName(itemName);
                // 物品数量（同一个物品，买入价格和时间可能不一样，因此记录也一样）
                long totalCount = v.stream().mapToLong(VirtualLocker::getCount).sum();
                data.setCount(totalCount);
                data.setVirtualLockerList(v);
                result.add(data);
            }

        });
        return result;
    }

}